// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.PageSearch;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.InventoryDetails;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.InventoryDetailsMapper;
import com.fowo.api.model.inventory.details.InventoryDetailsExcelPo;
import com.fowo.api.model.inventory.details.InventoryDetailsGetBinInventoryParam;
import com.fowo.api.model.inventory.details.InventoryDetailsGetBinInventoryResult;
import com.fowo.api.model.inventory.details.InventoryDetailsImportPo;
import com.fowo.api.model.inventory.details.InventoryDetailsItemVo;
import com.fowo.api.model.inventory.details.InventoryDetailsSearchParamPo;
import com.fowo.api.model.inventory.details.InventoryDetailsVo;
import com.fowo.api.model.inventory.details.InventoryDetailsWarehouseInventoryExcelPo;
import com.fowo.api.model.inventory.details.InventoryDetailsWarehouseInventoryParams;
import com.fowo.api.model.inventory.details.InventoryDetailsWarehouseInventoryResult;
import com.fowo.api.model.inventory.details.InventoryDetailsWarehouseStockExcelPo;
import com.fowo.api.model.inventory.details.InventoryDetailsWarehouseStockParams;
import com.fowo.api.model.inventory.details.InventoryDetailsWarehouseStockResult;
import com.fowo.api.service.InventoryDetailsService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 库存明细 服务实现基类
 * @author 蜂窝蜜造平台 配置人：陈新新，任凯
 */
@Slf4j
@DataObjectType(InventoryDetails.class)
@DS("ds24")
public class InventoryDetailsBaseServiceImpl
  extends ServiceImpl<InventoryDetailsMapper, InventoryDetails>
  implements InventoryDetailsService {

  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>();
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;
  /** 仓库库存 SQL 视图字段排序对应信息 */
  public static final Map<String, String> WAREHOUSESTOCK_SORT_MAP =
    Map.ofEntries();
  /** 仓位库存 SQL 视图字段排序对应信息 */
  public static final Map<String, String> WAREHOUSEINVENTORY_SORT_MAP =
    Map.ofEntries();

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected InventoryDetailsService self;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Resource
  protected Validator validator;

  /**
   * 创建库存明细
   * @param model 库存明细
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(InventoryDetailsVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    InventoryDetails entity = new InventoryDetails();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.save(entity)) {
      return entity.getId();
    }
    throw new Exception("库存明细保存失败");
  }

  /**
   * 更新库存明细
   * @param model 库存明细
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(InventoryDetailsVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    InventoryDetails entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("库存明细不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      return true;
    }
    return false;
  }/**
   * 更新库存明细（带空值）
   * @param model 库存明细
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(InventoryDetailsVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    InventoryDetails entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("库存明细不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(InventoryDetails::getLastUpdateTime, model.getLastUpdateTime())
      .set(InventoryDetails::getLastUpdateUser, model.getLastUpdateUser())
      .eq(InventoryDetails::getId, model.getId())
      .update();
    if (isOk) {}
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(InventoryDetailsSearchParamPo search) {
    return false;
  }

  /**
   * 删除库存明细
   * @param id 库存明细的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    return this.removeById(id);
  }

  /**
   * 批量删除库存明细
   * @param ids 库存明细的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<InventoryDetailsImportPo> excelToImportRow(
    InventoryDetailsImportPo row,
    Integer rowNumber,
    InventoryDetailsVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<InventoryDetailsImportPo> ir =
      new ImportRow<InventoryDetailsImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<InventoryDetailsImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new InventoryDetailsVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, InventoryDetailsImportPo.class);

    // 一般数据处理

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<InventoryDetailsImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<InventoryDetailsImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            InventoryDetailsImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              InventoryDetailsImportPo row,
              AnalysisContext cxt
            ) {
              InventoryDetailsVo vo = new InventoryDetailsVo();
              ImportRow<InventoryDetailsImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<InventoryDetailsImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<InventoryDetailsImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      InventoryDetailsVo vo = new InventoryDetailsVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    InventoryDetailsSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addStringFields();

      String fileName = String.format(
        "库存明细(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<InventoryDetailsExcelPo> items =
      new ArrayList<InventoryDetailsExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<InventoryDetailsItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<InventoryDetailsItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (InventoryDetailsItemVo item : list) {
        InventoryDetailsExcelPo excel = new InventoryDetailsExcelPo();
        BeanUtils.copyProperties(item, excel);

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "库存明细(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(InventoryDetailsExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过标题查询库存明细主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByName(String name) {
    return this.baseMapper.getIdByName(name);
  }

  /**
   * 通过标题查询库存明细多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByName(List<String> list) {
    return this.baseMapper.getIdsByName(list);
  }

  /**
   * 通过库存明细主键查询标题
   */
  @Override
  public String getNameById(Long id) {
    return this.baseMapper.getNameById(id);
  }

  /**
   * 通过库存明细主键查询标题列表
   */
  @Override
  public List<String> getNameByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getNameByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("name"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 库存明细的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public InventoryDetailsVo getVoById(Long id) throws Exception {
    InventoryDetailsVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }
    return vo;
  }

  /**
   * 分页查询库存明细
   * @param search 查询条件
   * @return 库存明细分页查询结果
   */
  @Override
  public Page<InventoryDetailsItemVo> pageSearch(
    InventoryDetailsSearchParamPo search
  ) {
    Page<InventoryDetailsItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(InventoryDetailsItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 库存明细快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'InventoryDetailsOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<InventoryDetailsItemVo>> searchOptions(
    InventoryDetailsSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询库存明细
   * @param search 查询条件
   * @return 库存明细列表查询结果
   */
  @Override
  public List<InventoryDetailsItemVo> search(
    InventoryDetailsSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询库存明细最后更新时间
   * @param search 查询条件
   * @return 库存明细最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(InventoryDetailsSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 仓库库存分页
   */
  @Override
  public Page<InventoryDetailsWarehouseStockResult> warehouseStockPage(
    InventoryDetailsWarehouseStockParams params
  ) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      params.setCurrentUserId(jwtUserInfo.getUserId());
    }

    params.initSort(" warehouse.id desc", WAREHOUSESTOCK_SORT_MAP);
    List<List<?>> lists = this.baseMapper.warehouseStockPage(params);
    Long total = Convert.toLong(
      CollUtil.getFirst(CollUtil.get(lists, 1)),
      Long.MAX_VALUE
    );
    Page resultPage = params.toPage();
    resultPage.setTotal(total).setRecords(CollUtil.get(lists, 0));
    return resultPage;
  }

  /**
   * 仓库库存导出
   */
  @DataActivity(action = SysDataActivityAction.Export)
  /**
   * 仓库库存导出是否需要后台执行
   */
  @Override
  public Boolean WarehouseStockBackgroundExportFlag(
    InventoryDetailsWarehouseStockParams params
  ) throws Exception {
    return true;
  }

  @Override
  public void WarehouseStockExport(
    Long templateId,
    InventoryDetailsWarehouseStockParams params,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      throw new RException("暂不支持模版！");
    }

    int current = 1;
    List<InventoryDetailsWarehouseStockExcelPo> items = new ArrayList<>();
    while (true) {
      params.setCurrent(current);
      params.setPageSize(EXPORT_QUERY_MAX_SIZE);
      Page<InventoryDetailsWarehouseStockResult> page = warehouseStockPage(
        params
      );
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<InventoryDetailsWarehouseStockResult> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (InventoryDetailsWarehouseStockResult item : list) {
        InventoryDetailsWarehouseStockExcelPo excel =
          new InventoryDetailsWarehouseStockExcelPo();
        BeanUtils.copyProperties(item, excel);

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }
    String fileName = String.format(
      "库存明细(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(InventoryDetailsWarehouseStockExcelPo.class)
      .doWrite(items);
  }

  /**
   * 仓库库存合计
   */
  @Override
  public Map warehouseStockSummary(
    InventoryDetailsWarehouseStockParams params
  ) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      params.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return this.baseMapper.warehouseStockSummary(params);
  }

  /**
   * 查询仓库下拉框
   */
  @Override
  public List<Map> warehouseStockwarehouseId() {
    return this.baseMapper.warehouseStockwarehouseId();
  }

  /**
   * 查询国家下拉框
   */
  @Override
  public List<Map> warehouseStockcountry() {
    return this.baseMapper.warehouseStockcountry();
  }

  /**
   * 查询店铺下拉框
   */
  @Override
  public List<Map> warehouseStockshopId() {
    return this.baseMapper.warehouseStockshopId();
  }

  /**
   * 查询分类下拉框
   */
  @Override
  public List<Map> warehouseStockclassify() {
    return this.baseMapper.warehouseStockclassify();
  }

  /**
   * 查询属性下拉框
   */
  @Override
  public List<Map> warehouseStockattribute() {
    return this.baseMapper.warehouseStockattribute();
  }

  /**
   * 查询品牌下拉框
   */
  @Override
  public List<Map> warehouseStockbrand() {
    return this.baseMapper.warehouseStockbrand();
  }

  /**
   * 仓位库存分页
   */
  @Override
  public Page<InventoryDetailsWarehouseInventoryResult> warehouseInventoryPage(
    InventoryDetailsWarehouseInventoryParams params
  ) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      params.setCurrentUserId(jwtUserInfo.getUserId());
    }

    params.initSort("p3.id desc", WAREHOUSEINVENTORY_SORT_MAP);
    List<List<?>> lists = this.baseMapper.warehouseInventoryPage(params);
    Long total = Convert.toLong(
      CollUtil.getFirst(CollUtil.get(lists, 1)),
      Long.MAX_VALUE
    );
    Page resultPage = params.toPage();
    resultPage.setTotal(total).setRecords(CollUtil.get(lists, 0));
    return resultPage;
  }

  /**
   * 仓位库存导出
   */
  @DataActivity(action = SysDataActivityAction.Export)
  /**
   * 仓位库存导出是否需要后台执行
   */
  @Override
  public Boolean WarehouseInventoryBackgroundExportFlag(
    InventoryDetailsWarehouseInventoryParams params
  ) throws Exception {
    return baseMapper.WarehouseInventoryTotal(params) > ExcelConfig.THRESHOLD;
  }

  @Override
  public void WarehouseInventoryExport(
    Long templateId,
    InventoryDetailsWarehouseInventoryParams params,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      throw new RException("暂不支持模版！");
    }

    int current = 1;
    List<InventoryDetailsWarehouseInventoryExcelPo> items = new ArrayList<>();
    while (true) {
      params.setCurrent(current);
      params.setPageSize(EXPORT_QUERY_MAX_SIZE);
      Page<InventoryDetailsWarehouseInventoryResult> page =
        warehouseInventoryPage(params);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<InventoryDetailsWarehouseInventoryResult> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (InventoryDetailsWarehouseInventoryResult item : list) {
        InventoryDetailsWarehouseInventoryExcelPo excel =
          new InventoryDetailsWarehouseInventoryExcelPo();
        BeanUtils.copyProperties(item, excel);

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }
    String fileName = String.format(
      "库存明细(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(InventoryDetailsWarehouseInventoryExcelPo.class)
      .doWrite(items);
  }

  /**
   * 仓位库存合计
   */
  @Override
  public Map warehouseInventorySummary(
    InventoryDetailsWarehouseInventoryParams params
  ) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      params.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return this.baseMapper.warehouseInventorySummary(params);
  }

  /**
   * 查询仓库下拉框
   */
  @Override
  public List<Map> warehouseInventorywarehouseId() {
    return this.baseMapper.warehouseInventorywarehouseId();
  }

  /**
   * 查询仓位类型下拉框
   */
  @Override
  public List<Map> warehouseInventorytype() {
    return this.baseMapper.warehouseInventorytype();
  }

  /**
   * 查询分类下拉框
   */
  @Override
  public List<Map> warehouseInventoryclassify() {
    return this.baseMapper.warehouseInventoryclassify();
  }

  /**
   * 查询属性下拉框
   */
  @Override
  public List<Map> warehouseInventoryattribute() {
    return this.baseMapper.warehouseInventoryattribute();
  }

  /**
   * 查询品牌下拉框
   */
  @Override
  public List<Map> warehouseInventorybrand() {
    return this.baseMapper.warehouseInventorybrand();
  }

  /**
   * 仓位库存
   */
  @Override
  public Page<InventoryDetailsGetBinInventoryResult> getBinInventory(
    InventoryDetailsGetBinInventoryParam param
  ) {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    if (currentUser != null) {
      param.setCurrentUserId(currentUser.getUserId());
    }
    param.setDisableDataPremissions(true);
    return this.baseMapper.getBinInventory(param.toPage(), param);
  }
}
